import service from "../common/service";
import dateRangUtil from "../common/dateRangUtil"
import { useMainStore } from "@/store/modules/store";

/**
 * @description 获取最新的 EnjoyCRM 值
 * @returns {string} EnjoyCRM
 */
const getEnjoyCRM = () => {
	const mainStore = useMainStore();
	const enjoyServiceIp = mainStore.enjoyServiceIp;
	const EnjoyCRM = enjoyServiceIp?.EnjoyCRM?.split('/Enjoy/Service')[0] || '';
	return EnjoyCRM;
};

/**
 * @description 获取最新的 EnjoyOA 值
 * @returns {string} EnjoyOA
 */
const getEnjoyOA = () => {
	const mainStore = useMainStore();
	const enjoyServiceIp = mainStore.enjoyServiceIp;
	const EnjoyOA = enjoyServiceIp?.EnjoyOA?.split('/Enjoy/Service')[0] || '';
	return EnjoyOA;
};

/**
 * @description 获取最新的 crmUrl
 * @returns {object} crmUrl
 */
const getCrmUrl = () => {
	const mainStore = useMainStore();
	const enjoyServiceIp = mainStore.enjoyServiceIp;
	const EnjoyOA = enjoyServiceIp?.EnjoyOA?.split('/Enjoy/Service')[0] || '';
	const EnjoyCRM = enjoyServiceIp?.EnjoyCRM?.split('/Enjoy/Service')[0] || '';
	const EnjoyMBMMain = enjoyServiceIp?.EnjoyMain?.split('/Enjoy/Service')[0] || '';
	return {
		mainApi: `${EnjoyOA}/main/api/Enjoy/Service`,
		crmApi: `${EnjoyCRM}/enjoycrm/api/Enjoy/Service`,
		mbmApi: `${EnjoyMBMMain}/Enjoy/Service`,
	};
};

/**
 * @description crm请求
 * @param {string} url 请求地址
 * @param {string} uniqueKey 唯一标识
 * @param {string} methodName 方法名
 * @param {object} objectData 请求参数
 * @param {string} billType 单据类型
 * @returns {Promise} Promise
 */
const crmRequest = async (url, uniqueKey, methodName, objectData : any = undefined, billType = '', tag = null) => {
	return new Promise((resolve, reject) => {
		let request = {
			url,
			data: {
				UniqueKey: uniqueKey,
				MethodName: methodName,
				ObjectData: objectData,
				BillType: billType,
				Tag: tag
			},
		};
		service.request(request, (res) => {
			if (res && res.data) {
				if (!res.data.HasException) {
					resolve(res.data.ObjectData);
				} else {
					uni.showToast({
						duration: 3500,
						icon: 'none',
						title: res.data.Exception.Message,
						mask: true,
					});
					reject(res.data.Exception.Message);
				}
			}
		}, () => {
			console.log('请求失败');
			reject('请求失败');
		});
	});
};


/**
 * @description crm请求
 * @param {string} url 请求地址
 * @param {string} uniqueKey 唯一标识
 * @param {string} methodName 方法名
 * @param {object} objectData 请求参数
 * @param {string} billType 单据类型
 * @returns {Promise} Promise
 */
const crmRequestAsync = async (url, uniqueKey, methodName, objectData : any = undefined, billType = '') => {
	return new Promise((resolve, reject) => {
		let request = {
			url,
			data: {
				UniqueKey: uniqueKey,
				MethodName: methodName,
				ObjectData: objectData,
				BillType: billType,
			},
		};
		service.request(request, (res) => {
			if (res && res.data) {
				resolve(res.data);
			}
		}, () => {
			console.log('请求失败');
			reject('请求失败');
		});
	});
};


// 刷新token
const refreshToken = async () => {
	const crmUrl = getCrmUrl();
	const EXPIRES = 1000 * 60 * 2; // 提前失效前2分钟刷新
	const mainStore = useMainStore();
	const { sUser, dServerDt, idsToken } = mainStore.loginInfo
	const { expires_in, refresh_token } = idsToken; // 令牌的有效期（以秒为单位）
	// 计算令牌的过期时间
	let tokenExpirationTime = new Date(dServerDt).getTime() + (expires_in * 1000);
	// 获取当前时间
	let now = new Date().getTime();
	let isExpires = tokenExpirationTime <= now + EXPIRES;
	// console.log("---------refreshToken---------", expires_in, refresh_token, sUser, dServerDt, isExpires )
	// 判断令牌是否过期
	if (isExpires) {
		// token 即将失效，更新token
		// console.log("Token is expired");
		let req = {
			sRefreshToken: refresh_token,
			userNo: sUser,
		}
		// console.log('--------store.state.loginInfo---------: ', store.state.loginInfo)
		service.enjoyShowLoading('正在刷新Token...');
		const tokenResult = await crmRequest(crmUrl.mbmApi, '管易通40公共', 'RefreshCenterToken', req);
		// if (tokenResult  && tokenResult.refresh_token ) {
		//   store.commit('loginInfoin', {
		//     ...store.state.loginInfo,
		//     dServerDt: dateRangUtil.formatDate(),
		//     idsToken: tokenResult
		//   })
		// }
		service.enjoyHideLoading();
	} else {
		// token 失效时间大于2分钟
		// console.log("Token is not expired");
	}
}

export {
	crmRequest,
	crmRequestAsync,
	refreshToken,
	getEnjoyOA,
	getEnjoyCRM,
	getCrmUrl
};